package com.app.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.DynamicLayout;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

import com.caszx.chargingpile.R;

public class FoldableTextView extends TextView implements View.OnClickListener {

	private static final String ELLIPSIS_TWO_DOTS = "‥";
	/** 是否边缘对齐 */
	private boolean mAlignViewEdge = false;
	/** 是否能折叠 */
	private boolean mClickToFold = true;
	private CharSequence mEllipseText;   //..
	private CharSequence mUnfoldText;  //更多
	/**折叠后显示的最多行数*/
	private int mFoldLineMax;           //显示的最多行数
	
	private boolean mIsClickSpan = false;
	/**是否是折叠状态*/
	private boolean mIsfolded = true;   
	private int mLinkColor = -1;
	
	private FoldingListener mListener;
	private CharSequence mainText;
	private SpannableStringBuilder sb ;
	
	public FoldableTextView(Context paramContext) {
		this(paramContext, null);
	}

	public FoldableTextView(Context paramContext, AttributeSet paramAttributeSet) {
		this(paramContext, paramAttributeSet,
				R.style.Widget_USXCommon_FoldableTextView);
	}

	public FoldableTextView(Context context, AttributeSet paramAttributeSet,
			int paramInt) {
		super(context, paramAttributeSet, paramInt);
		TypedArray localTypedArray = context.obtainStyledAttributes(
				paramAttributeSet, R.styleable.FoldableTextView, paramInt, 0);
		mEllipseText = localTypedArray
				.getText(R.styleable.FoldableTextView_mzTextEllipse);
		mUnfoldText = localTypedArray
				.getText(R.styleable.FoldableTextView_mzTextUnfold);
		mFoldLineMax = localTypedArray.getInt(
				R.styleable.FoldableTextView_mzMaxFoldLine, 0);
		mAlignViewEdge = localTypedArray.getBoolean(
				R.styleable.FoldableTextView_mzUnfoldAlignViewEdge, false);
		mClickToFold = localTypedArray.getBoolean(
				R.styleable.FoldableTextView_mzClickToFold, false);
		mLinkColor = localTypedArray.getColor(
				R.styleable.FoldableTextView_mzLinkColor, -1);
		mIsfolded = localTypedArray.getBoolean(
				R.styleable.FoldableTextView_mzIsFold, true);
		localTypedArray.recycle();
		if (TextUtils.isEmpty(this.mUnfoldText)) {
			this.mUnfoldText = context.getString(R.string.more_item_label);
		}
		if (TextUtils.isEmpty(this.mEllipseText)) {
			this.mEllipseText = ELLIPSIS_TWO_DOTS;
		}
		setMovementMethod(LinkMovementMethod.getInstance());
		setOnClickListener(true);
	}
	
	private CharSequence foldText(CharSequence text) {
		if(sb!=null && sb.length()>0) return sb;
		 sb = new SpannableStringBuilder(text);
		Layout layout = getLayout();
		DynamicLayout tmpLayout = new DynamicLayout(sb, layout.getPaint(),
				layout.getWidth(), layout.getAlignment(), 1.0f, 0, false);
		//字数行数<= 最大折叠行数，直接返回
		if (tmpLayout.getLineCount()<= mFoldLineMax) return sb;
		
		//得到指定行数的最后一个可见字符的位置,不计算空格,tab,换行符
		int en = tmpLayout.getLineVisibleEnd(mFoldLineMax-1);
		MoreClickSpan span = new MoreClickSpan(sb);
		if (!TextUtils.isEmpty(mEllipseText)) {
			//替换需要折叠的文字
			int start = en-mEllipseText.length()-mUnfoldText.length();
			start = start<0?0:start;
			sb.delete(start, sb.length());
			String txt = sb.toString().trim();
			sb.clear();
			sb.append(txt);
			sb.replace(txt.length(), txt.length(), mEllipseText);
		}else {
			//删除从en开始以后的所有的字符
			int start = en-mEllipseText.length();
			start = start<0?0:start;
			sb.delete(en-mUnfoldText.length(), sb.length());
		}
		
		//现在的字符是经过删减的。要把"更多"插进来的下一个位置
		int addIndex = sb.length();
		sb.append(mUnfoldText);
		sb.setSpan(span, addIndex, sb.length(), Spanned.SPAN_POINT_MARK);
		if(!mAlignViewEdge) return sb;
		
		if(tmpLayout.getLineCount() < mFoldLineMax){
			mFoldLineMax--;
		}
		ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.TRANSPARENT);
		int colorStart = addIndex;
		while (tmpLayout.getLineCount() == mFoldLineMax) {
			sb.replace(addIndex, addIndex, "#");
			addIndex++ ;
		}
		sb.setSpan(colorSpan, colorStart, addIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		
		//"更多"靠右对其,经过上面的循环,现在的行数是mFoldLineMax+1，
		//"更多"里的"多"在下一行,多出一个字符,所以删除前一个字符
		sb.delete(addIndex-1, addIndex);
		return sb;
	}

	private void setOnClickListener(boolean paramBoolean) {
		if (paramBoolean) {
			setOnClickListener(this);
			return;
		}
		setOnClickListener(null);
	}

	public boolean getFoldStatus() {
		return mIsfolded;
	}

	@Override
	public void onClick(View view) {
//		if(mIsClickSpan||!mClickToFold){
//			mIsClickSpan = false;
//			return;
//		}
		if (mIsfolded) {
			//已经折叠了，更改状态
			mIsfolded = false;
			setText(mainText, BufferType.NORMAL);
			if (mListener != null) mListener.onFolding(this, false);
		} else {
			mIsfolded = true;
			setText(foldText(mainText));
			if (mListener != null) mListener.onFolding(this, true);
		}
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		if (!mIsfolded || mFoldLineMax <= 0)return;
		
		if(mainText == null || TextUtils.isEmpty(getText())){
			mainText = getText();
		}
		
		if (mainText != null && (mainText instanceof Spanned)) {
			CharSequence dst = foldText(mainText);
			if (!TextUtils.equals(mainText, dst)|| (mListener != null && mListener.onFolding(this, true))) {
				setText(dst, BufferType.SPANNABLE);
			}
		}
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}

	public void setClickToFold(boolean clickToFold) {
		mClickToFold = clickToFold;
	}

	public void setFoldStatus(boolean foldStatus) {
		if (this.mIsfolded != foldStatus) {
			this.mIsfolded = foldStatus;
			requestLayout();
			invalidate();
		}
	}

	public void setFoldText(String ellipseText, String unfoldText,
			boolean isAlignViewEdge) {
		this.mAlignViewEdge = isAlignViewEdge;
		if (ellipseText != null) {
			mEllipseText = ellipseText;
		}
		if (unfoldText != null) {
			mUnfoldText = unfoldText;
		}
	}

	public void setFolding(int foldLineMax, FoldingListener listener) {
		this.mFoldLineMax = foldLineMax;
		this.mListener = listener;
		if (mFoldLineMax > 0) {
			requestLayout();
			invalidate();
		}
	}

	public void setLinkColor(int paramInt) {
		this.mLinkColor = paramInt;
		invalidate();
	}

	@Override
	public void setText(CharSequence paramCharSequence,
			BufferType paramBufferType) {
		super.setText(paramCharSequence, paramBufferType);
		requestLayout();
	}

	public static abstract interface FoldingListener {
		public abstract boolean onFolding(FoldableTextView textView,
										  boolean isfolded);
	}

	private class MoreClickSpan extends ClickableSpan {
		private final CharSequence mText;

		public MoreClickSpan(CharSequence text) {
			this.mText = text;
		}

		@Override
		public void onClick(View view) {
			if ((mListener != null)&& (!mListener.onFolding(FoldableTextView.this, false))) {
				return;
			}
			//不是折叠状态
//			mIsfolded  = false;
//			setText(mText, TextView.BufferType.NORMAL);
//			mIsClickSpan  = true;
		}

		@Override
		public void updateDrawState(TextPaint textPaint) {
			if (mLinkColor == -1) {
				textPaint.setColor(textPaint.linkColor);
				return;
			}
			textPaint.setColor(mLinkColor);
		}
	}
}
